package com.ms.oschina.fragment;

import java.io.IOException;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.view.View.OnClickListener;

import com.ms.oschina.adapter.ActivitiesAdapter;
import com.ms.oschina.adapter.PageIndexListAdapter;
import com.ms.oschina.api.remote.OsChinaApi;
import com.ms.oschina.base.BaseListFragment;
import com.ms.oschina.bean.Constants;
import com.ms.oschina.bean.Event;
import com.ms.oschina.util.LocalBroadcastUtils;
import com.ms.oschina.util.LogUtils;
import com.ms.oschina.util.PreferenceUtils;
import com.ms.oschina.util.UiUtils;

public class ActivitiesInfoFragment extends BaseListFragment<Event> {

	private UserUpdateReceiver mReceiver;

	@Override
	public PageIndexListAdapter<Event> getAdapter() {
		ActivitiesAdapter adapter = new ActivitiesAdapter(getListView(),
				getNetData(), true);
		int mark = getMark();
		adapter.setMark(mark);
		return adapter;
	}

	@Override
	public List<Event> getNetData(int pageIndex) throws IOException {
		int mark = getMark();

		List<Event> list = null;
		int uid = 0;

		switch (mark) {
		case ActivitiesFragment.NEW_EVENT:
			list = OsChinaApi.getActivitiesList(pageIndex, uid);
			break;
		case ActivitiesFragment.MY_EVENT:
			uid = PreferenceUtils.getPrefInt(UiUtils.getContext(),
					Constants.UID, -1);
			if (uid != -1) {// 已经登录
				list = OsChinaApi.getActivitiesList(pageIndex, uid);
			}

			if (list == null) {// 用户未登陆
				setErrorPager("请登陆后操作", new OnClickListener() {
					@Override
					public void onClick(View v) {
						UiUtils.login();
					}
				});
			}
			break;
		}

		return list;
	}

	@Override
	public void initEvent() {
		mReceiver = new UserUpdateReceiver();
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(Constants.ACTION_EXTERNAL_USERCHANGE);
		LocalBroadcastUtils.registerReceiver(intentFilter, mReceiver);
	}

	@Override
	public void onDestroy() {
		LogUtils.e("onDestroy::::::::;");
		LocalBroadcastUtils.unRegisterReceiver(mReceiver);
		mReceiver = null;
		super.onDestroy();
	}

	private class UserUpdateReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			LogUtils.e("refreshData::::::::;");
			refreshData();
		}
	}

}
